import { Workbook } from 'exceljs'
import FileSaver from 'file-saver'
import { ExcelParams } from '@renderer/utils/vendor'
import dayjs from 'dayjs'
import { AccountsResItem } from '@renderer/api/statement'
import { add, isEmpty } from 'lodash-es'
import { decimalRound } from '@renderer/utils/mixins'
import { useUserStore } from '@renderer/store'

function formatData(baseData: any[]): any[] {
  return baseData
    ?.map((item) => {
      const serialNumber = '本期收货明细'

      function dataAssembly(item) {
        const deliveryDate = item.deliveryDate ? dayjs(item.deliveryDate).format('YY-MM-DD') : ''
        const productName = item.productName ?? ''
        const specModel = item.specModel ?? ''
        const unit = item.unit ?? ''
        const qty = item.qty ?? ''
        const unitPrice = decimalRound(item.unitPrice)
        const amount = decimalRound(item.qty! * item.unitPrice!, 4)
        const isInclTax = item.isInclTax ? '含税' : '不含税'
        const remark = ''
        return [
          deliveryDate,
          productName,
          specModel,
          unit,
          qty,
          unitPrice,
          amount,
          isInclTax,
          remark
        ]
      }

      if (!isEmpty(item.detailList)) {
        return item.detailList?.map((detailItem, index) => {
          if (index === 0) {
            const dataItem = dataAssembly({ ...detailItem, ...item, span: item.detailList.length })
            return [serialNumber, ...dataItem]
          } else {
            const dataItem = dataAssembly({ ...detailItem, ...item })
            return [serialNumber, ...dataItem]
          }
        })
      } else {
        const dataItem = dataAssembly(item)
        return [serialNumber, ...dataItem]
      }
    })
    .flat()
}

// 对账单导出打印
export function exportExcel(excelTableData: AccountsResItem, fileName: string) {
  return new Promise((resolve) => {
    const exportParam: ExcelParams = { isDownload: true }
    const workbook = new Workbook()
    const sheetNames = ['Sheet1']
    sheetNames.forEach((sheetItem) => {
      const worksheet = workbook.addWorksheet(sheetItem)
      // 获取到工作表头的数据
      const headerData = [
        { width: 6 }, // 序号
        { width: 10 }, // 日期
        { width: 15 }, // 产品名称
        { width: 12 }, // 规格
        { width: 5 }, // 单位
        { width: 6 }, // 数量
        { width: 8 }, // 单价
        { width: 12 }, // 金额
        { width: 8 }, // 含税
        { width: 10 } // 备注
      ]

      //生成列
      worksheet.columns = headerData.map((item) => {
        const col: any = {
          width: item.width
        }
        return col
      })

      // 标题
      worksheet.mergeCells('A1:J1')
      const titleCell = worksheet.getCell('A1')
      titleCell.value = `${dayjs(excelTableData.billEndDate).format('YYYY年MM月')}采购对账单`
      titleCell.font = { size: 20, bold: true }
      titleCell.alignment = { vertical: 'middle', horizontal: 'center' }
      // 表单信息
      worksheet.mergeCells('A2:E2')
      worksheet.getCell('A2').value = `单位名称:${excelTableData.supplierName}`
      // worksheet.getCell('A2').font = { size: 14 }
      worksheet.getCell('A2').alignment = { vertical: 'middle', horizontal: 'left' }
      worksheet.mergeCells('F2:J2')
      const dateRangeCell = worksheet.getCell('F2')
      dateRangeCell.value = `账单起始日期:${dayjs(excelTableData.billStartDate).format('YYYY年MM月DD')}至${dayjs(excelTableData.billEndDate).format('YYYY年MM月DD')}`
      dateRangeCell.font = { color: { argb: 'FFFF0000' } }
      dateRangeCell.alignment = { vertical: 'middle', horizontal: 'right' }
      // 表头
      const headers = [
        '序号',
        '日期',
        '产品名称',
        '规格',
        '单位',
        '数量',
        '单价',
        '金额（元）',
        '含税',
        '备注'
      ]
      worksheet.addRow(headers)
      const headerRow = worksheet.getRow(3)
      // headerRow.height = 20
      headerRow.font = { bold: true }
      headerRow.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }
      // 表格数据
      const tableData = formatData(excelTableData.detailList) ?? [[]]
      tableData.forEach((item) => {
        worksheet.addRow(item)
      })
      const tableNum = tableData.length + 3
      worksheet.mergeCells(`A4:A${tableNum}`)
      worksheet.getCell(`A4:A${tableNum}`).alignment = { wrapText: true }
      worksheet.getCell(`C4:C${tableNum}`).alignment = { wrapText: true }
      // 汇总区块
      const summaryData = [
        ['本期应支付', '', '含税', '', '', '', '', excelTableData.curReceivableAmt, '', ''],
        ['', '', '不含税', '', '', '', '', excelTableData.curReceivableExclTaxAmt, '', ''],
        [
          '',
          '',
          '合计',
          '',
          '',
          '',
          '',
          add(excelTableData.curReceivableExclTaxAmt, excelTableData.curReceivableAmt),
          '',
          ''
        ],
        [
          '上期末剩余未支付',
          '',
          '对公',
          '',
          '',
          '',
          '',
          excelTableData.historyUnreceiveAmt,
          '',
          ''
        ],
        ['', '', '对私', '', '', '', '', excelTableData.historyUnreceiveExclTaxAmt, '', ''],
        [
          '',
          '',
          '合计',
          '',
          '',
          '',
          '',
          add(excelTableData.historyUnreceiveAmt, excelTableData.historyUnreceiveExclTaxAmt || 0),
          '',
          ''
        ],
        ['本期已支付明细', '', '对公', '', '', '', '', excelTableData.curReceivedAmt, '', ''],
        ['', '', '对私', '', '', '', '', excelTableData.curReceivedExclTaxAmt, '', ''],
        [
          '',
          '',
          '合计',
          '',
          '',
          '',
          '',
          add(excelTableData.curReceivedAmt || 0, excelTableData.curReceivedExclTaxAmt || 0),
          '',
          ''
        ],
        ['核销', '', '对私', '', '', '', '', excelTableData.writeAmt, '', ''],
        [
          '本期末累计未收取',
          '',
          '对公',
          '',
          '',
          '',
          '',
          excelTableData.remainReceivableAmt,
          '',
          ''
        ],
        ['', '', '对私', '', '', '', '', excelTableData.remainReceivableExclTaxAmt, '', ''],
        [
          '',
          '',
          '合计',
          '',
          '',
          '',
          '',
          add(
            excelTableData.remainReceivableAmt || 0,
            excelTableData.remainReceivableExclTaxAmt || 0
          ),
          '',
          ''
        ]
      ]
      worksheet.addRows(summaryData)
      for (let index = 0; index < 3; index++) {
        worksheet.mergeCells(`A${tableNum + 1 + 3 * index}:B${tableNum + 3 + 3 * index}`)
        worksheet.mergeCells(`C${tableNum + 1 + 3 * index}:G${tableNum + 1 + 3 * index}`)
        worksheet.mergeCells(`C${tableNum + 2 + 3 * index}:G${tableNum + 2 + 3 * index}`)
        worksheet.mergeCells(`C${tableNum + 3 + 3 * index}:G${tableNum + 3 + 3 * index}`)
      }
      worksheet.mergeCells(`A${tableNum + 1 + 9}:B${tableNum + 1 + 9}`)
      worksheet.mergeCells(`C${tableNum + 1 + 9}:G${tableNum + 1 + 9}`)

      worksheet.mergeCells(`A${tableNum + 1 + 1 + 9}:B${tableNum + 3 + 1 + 9}`)
      worksheet.mergeCells(`C${tableNum + 1 + 1 + 9}:G${tableNum + 1 + 1 + 9}`)
      worksheet.mergeCells(`C${tableNum + 2 + 1 + 9}:G${tableNum + 2 + 1 + 9}`)
      worksheet.mergeCells(`C${tableNum + 3 + 1 + 9}:G${tableNum + 3 + 1 + 9}`)

      // ===== 页脚 =====
      const footerNum = tableNum + 3 + 1 + 9 + 1
      worksheet.mergeCells(`A${footerNum}:E${footerNum}`)
      const userStore = useUserStore().localUserInfo
      worksheet.getCell(`A${footerNum}`).value = userStore.tenantName
      worksheet.getCell(`A${footerNum}`).alignment = { horizontal: 'left' }

      worksheet.mergeCells(`F${footerNum}:J${footerNum}`)
      worksheet.getCell(`F${footerNum}`).value = excelTableData.supplierName
      worksheet.getCell(`F${footerNum}`).alignment = { horizontal: 'center' }

      worksheet.mergeCells(`A${footerNum + 1}:E${footerNum + 1}`)
      worksheet.getCell(`A${footerNum + 1}`).value = `制表日期：${dayjs().format('YYYY年M月DD日')}`
      worksheet.getCell(`A${footerNum + 1}`).alignment = { horizontal: 'left' }

      worksheet.mergeCells(`F${footerNum + 1}:J${footerNum + 1}`)
      worksheet.getCell(`F${footerNum + 1}`).value = `日期：${dayjs().format('YYYY年M月DD日')}`
      worksheet.getCell(`F${footerNum + 1}`).alignment = { horizontal: 'center' }

      // 样式
      worksheet.eachRow((row, rowNumber) => {
        if (rowNumber >= 3 && rowNumber <= tableNum + 3 + 1 + 9) {
          row.alignment = { vertical: 'middle', horizontal: 'center' }
          row.eachCell((cell) => {
            cell.border = {
              top: { style: 'thin' },
              left: { style: 'thin' },
              bottom: { style: 'thin' },
              right: { style: 'thin' }
            }
          })
        }
      })

      workbook.xlsx.writeBuffer().then((buffer) => {
        //这里为type
        const blob = new Blob([buffer], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
        })
        if (exportParam.isDownload) {
          FileSaver(blob, `${fileName}.xlsx`)
        }
        resolve(blob)
      })
    })
  })
}
